<template>
  <base-breadcrumb :title="titleName">
    <searchData
      :search-data="searchArr"
      @search="search"
    />

    <a-card :bordered="false">
      <!-- <title-name title="分包商列表" /> -->

      <div class="table-operator">
        <a-button
          v-btnPermission="'pm_017_syn_04'"
          type="primary"
          @click="synchronousData"
        >
          同步云筑集采分包商数据
        </a-button>
        <excel
          ref="exportComponent"
          :is-click-generate="'false'"
          file-name="分包商台账"
        >
          <a-button
            slot="excelBtn"
            :loading="loadingState.isExport"
            type="primary"
            @click="exportLaborDataReq"
          >
            导出
          </a-button>
        </excel>
      </div>

      <div class="pub-table-select-count">
        <a-icon
          type="info-circle"
          theme="twoTone"
        />
        <span style="margin-right: 12px"> 分包商总计：<span class="totalNum">{{ nodeDeltails.totalCount }} 个</span> |
          合格分包商：<span class="totalNum">{{ nodeDeltails.qualifiedCount }} 个</span> |
          不合格分包商：<span class="totalNum">{{ nodeDeltails.unqualifiedCount }} 个</span>  |
          拉黑分包商：<span class="totalNum">{{ nodeDeltails.blockCount }} 个</span> |
          暂停投标使用分包商：<span class="totalNum">{{ nodeDeltails.temporarilyCount }} 个</span>
        </span>
      </div>

      <list-table
        ref="table"
        size="default"
        :row-key="record => record.id"
        :columns="columns"
        :request="loadData"
        :alert="true"
        show-size-changer
        show-quick-jumper
        show-pagination="auto"
      >
        <span
          slot="serial"
          slot-scope="text, record, index"
        >{{ index + 1 }}</span>
        <span
          slot="type"
          slot-scope="text"
        >
          <ellipsis
            :length="16"
            tooltip
          >{{ text }}</ellipsis>
        </span>
        <span
          slot="representative"
          slot-scope="text, record"
        >
          {{ record.representative }}

          <span v-if="record.legalPhone != null">/{{ record.legalPhone }}</span>
        </span>
        <span
          slot="contactPhone"
          slot-scope="text, record"
        >
          {{ record.contacts }}
          <span v-if="record.contactPhone != null ">/{{ record.contactPhone }}</span>
        </span>
        <span
          slot="address"
          slot-scope="text"
        >
          <ellipsis
            :length="16"
            tooltip
          >{{ text }}</ellipsis>
        </span>
        <span
          slot="action"
          slot-scope="text, record"
        >
          <template>
            <!--<a @click="handleSub(record)">查看</a>-->
            <!--<a-divider type="vertical"/>-->
            <a
              v-btnPermission="'pm_017_alt_02'"
              @click="handleEdit(record)"
            >状态变更</a>
          </template>
        </span>
      </list-table>


      <a-modal
        v-model="visible"
        title="分包商状态变更"
        :width="900"
      >
        <template slot="footer">
          <a-button
            key="back"
            @click="handleCancel"
          >
            取消
          </a-button>
          <a-button
            key="submit"
            :loading="loading"
            type="primary"
            @click="handleOk"
          >
            确定
          </a-button>
        </template>
        <a-form-model
          ref="form1"
          :model="form"
          :rules="rules"
        >
          <a-row :gutter="24">
            <a-col
              :md="12"
              :sm="12"
            >
              <a-form-model-item
                label="分包商名称"
                :label-col="{lg: {span: 7}, sm: {span: 7}}"
                :wrapper-col="{lg: {span:17}, sm: {span: 17} }"
              >
                <BaseInput
                  v-model="form.subcontractors"
                  placeholder=" "
                  disabled
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :md="12"
              :sm="12"
            >
              <a-form-model-item
                label="状态"
                :label-col="{lg: {span: 7}, sm: {span: 7}}"
                :wrapper-col="{lg: {span:17}, sm: {span: 17} }"
                prop="statusCode"
              >
                <a-select v-model="form.statusCode">
                  <a-select-option
                    v-for="item in statusCodes"
                    :key="item.id"
                    :value="item.code"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row
            v-if="form.statusCode === '2'"
            :gutter="24"
          >
            <a-col
              :md="12"
              :sm="12"
            >
              <a-form-model-item
                label="暂停投标时间"
                :label-col="{lg: {span: 7}, sm: {span: 7}}"
                :wrapper-col="{lg: {span:17}, sm: {span: 17} }"
                prop="timeCode"
              >
                <a-select v-model="form.timeCode">
                  <a-select-option
                    v-for="item in times"
                    :key="item.id"
                    :value="item.code"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </a-modal>
    </a-card>
  </base-breadcrumb>
</template>

<script>
import excel from '@/components/excel/excel.vue'
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import {
  getLaborSubcontractors,
  getLaborSubcontractorsTotal,
  editLaborSubcontractors,
  getStatusCodeData,
  synchronousDatas,
  exportLaborData
} from '@/api/subcontractors/labor'
import { getLabelTypes } from '@/api/commons'


import ARow from 'ant-design-vue/es/grid/Row'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司选择框
import OrgTreeSelect from '@/components/OrgTreeSelect'
const columns = [
  {
    title: '序号',
    width: 80,
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '分包商名称',
    width: 100,
    dataIndex: 'subcontractors',
    ellipsis: true
  },
  {
    title: '所属分公司',
    width: 100,
    dataIndex: 'branch'
  },
  {
    title: '分包商类型',
    dataIndex: 'type',
    width: 100,
    // scopedSlots: { customRender: 'type' }
  },
  {
    title: '级别',
    width: 100,
    dataIndex: 'level'
  },
  {
    title: '统一社会信用代码',
    width: 140,
    dataIndex: 'licenseNum'
  },
  {
    title: '合作年限',
    width: 100,
    dataIndex: 'cooperation'
  },
  {
    title: '资质证书编号',
    width: 120,
    dataIndex: 'certificateNum'
  },
  {
    title: '资质等级',
    width: 100,
    dataIndex: 'certificateLevel'
  },
  {
    title: '安全生产许可证编号',
    width: 140,
    dataIndex: 'productionNum'
  },
  {
    title: '注册资金(万)',
    width: 120,
    dataIndex: 'registeredCapital'
  },
  {
    title: '法人代表及电话',
    width: 120,
    dataIndex: 'representative',
    scopedSlots: { customRender: 'representative' }
  },
  {
    title: '联系人及电话',
    width: 120,
    dataIndex: 'contactPhone',
    scopedSlots: { customRender: 'contactPhone' }
  },
  {
    title: '详细地址',
    dataIndex: 'address',
    width: 100,
    // scopedSlots: { customRender: 'address' }
  },
  {
    title: '当前所在项目',
    dataIndex: 'inProject',
    width: 300,
    ellipsis: true
  },
  {
    title: '入库时间',
    width: 120,
    dataIndex: 'storageTime'
  },
  {
    title: '暂停投标截止时间',
    width: 140,
    dataIndex: 'closingTime'
  },
  {
    title: '状态',
    width: 120,
    dataIndex: 'statusName'
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 140,
    fixed: 'right',
    scopedSlots: { customRender: 'action' }
  }
]
import api from '@/api/project/typeMaintenance.js'

export default {
  name: 'a' + Date.now(),
  components: {
    excel,
    ARow,
    STable,
    Ellipsis
  },
  filters: {
    statusFilter(type) {
      return statusMap[type].text
    },
    statusTypeFilter(type) {
      return statusMap[type].status
    }
  },
  data() {
    this.columns = columns
    return {
      loadingState: {
        isExport: false
      },
      loading: false,
      statusCodes: [],
      times: [],
      form: {
        subcontractors: '',
        statusCode: '',
        timeCode: ''
      },
      rules: {
        statusCode: [{ required: true, message: '请选择状态', trigger: 'change' }],
        timeCode: [{ required: true, message: '请选择暂停投标时间', trigger: 'change' }]
      },

      searchArr: [
        {
          name: '所属单位',
          valueKey: 'searchQuery',
          type: OrgTreeSelect,
        },
        // {
        //   name: '分公司',
        //   valueKey: 'branchComId',
        //   type: SelectSubCompany
        // },
        {
          name: '分包商名称',
          value: 'subcontractorName',
          type: 'input'
        },
        {
          name: '分包商类型',
          value: 'typeId',
          type: 'tree-select',
          attrs: {
            allowClear:true,
            replaceFields: { children: 'children', title: 'name', key: 'id', value: 'id' }
          },
          data: []
        },
        {
          name: '级别',
          value: 'level',
          type: 'select',
          data: []
        },
        {
          name: '统一社会信用代码',
          value: 'licenseNum',
          type: 'input'
        },
        {
          name: '合作年限',
          value: 'year',
          type: 'rangeInput',
          setInitValue: true,
          // initValue: undefined,
          attr: {
            rangeFormat: ['startYear', 'endYear'],
            min: 0
          }
        },
        {
          name: '状态',
          value: 'statusCode',
          type: 'select',
          data: []
        }
      ],

      nodeDeltails: {}, // 分包商汇总详情
      titleName: '',
      // create model
      visible: false,
      visibles: false,
      confirmLoading: false,
      mdl: null,
      mdls: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return getLaborSubcontractors(requestParameters)
          .then(res => {
            return res
          })
      },
      selectedRowKeys: [],
      selectedRows: [],
      isEdit: false,
      calType: []
    }
  },
  created() {
    this.getSubtotalDeltails()
    this.getStatusCodeData()
    this.getTypes()
    this.getTreeData()
  },
  methods: {
    async getTreeData() {
      let res = await api.labelTreeList()
      if (res.code === 200) {
        this.searchArr[2].data = this.allEnabledDigui(res.data)
      }
    },
    allEnabledDigui(list) {
      let r = []
      list.map(v => {
        v.disabled = false
        if (v.children && v.children.length) {
          v.children = this.allEnabledDigui(v.children)
        }
        r.push(v)
      })
      return r
    },
    removeDisabledDigui(list) {
      let r = []
      list.map(v => {
        if (!v.disabled) {
          if (v.children && v.children.length) {
            v.children = this.removeDisabledDigui(v.children)
          }
          r.push(v)
        }
      })
      return r
    },
    /**
     * 导出分包商台账数据
     */
    async exportLaborDataReq() {
      try {
        if (this.loadingState.isExport) {
          return
        }
        this.loadingState.isExport = true
        const res = await exportLaborData(this.queryParam)
        // 导出数据，对特殊字段进行处理
        const exportData = res.data.map(item => {
          return {
            ...item,
            representative: item.legalPhone ? item.representative + '/' + item.legalPhone : item.representative,
            contactPhone: item.contactPhone ? item.contacts + '/' + item.contactPhone : item.contacts
          }
        })
        // 导出列
        const columns = this.columns.filter(item => {
          return item.dataIndex !== 'action'
        })
        this.$refs.exportComponent.generateExcel(exportData, { columns: columns })
      } catch (e) {
        console.error(e)
      }
      this.loadingState.isExport = false
    },
    // 同步云筑集采分包商数据
    synchronousData() {
      let that = this
      that.$confirm({
        title: '同步云筑集采分包商信息',
        content: '本次同步时间略长，待同步完成后，您可在【事项】—【通知消息】—【待读消息】中查看结果，确实是否同步？',
        onOk() {
          return new Promise((resolve, reject) => {
            // 避免同步时间太长，点击之后立即关闭弹窗
            resolve()
            synchronousDatas().then(res => {
              if (res.data.code == 200 || res.code == 200) {
                that.$message.success('数据同步成功！')
                that.$refs.table.refresh(true)
              } else {
                that.$message.error('数据同步失败！')
              }
            }).catch((e) => {
              that.$message.error(e)
            }).finally(() => {
              resolve()
            })
          })
        },
        onCancel() {
        }
      })
    },
    getTypes() {
      getLabelTypes({ type: 1 }).then(res => {
        this.searchArr[3].data = this.getChangeDatatTypes(res.data)
      })
    },

    getStatusCodeData() {
      getStatusCodeData({ type: 4, enabledCode: 1 }).then(res => {
        this.statusCodes = res.data

        let arr = []
        res.data.forEach(function(obj, i) {
          let item = {}
          if (obj) {
            item.value = obj.id
            item.label = obj.name
          }
          arr.push(item)
        })
        this.searchArr[6].data = arr

      })

      getStatusCodeData({ type: 5, enabledCode: 1 }).then(res => {
        this.times = res.data
      })
    },
    getSubtotalDeltails() {
      getLaborSubcontractorsTotal(this.queryParam).then(res => {
        this.nodeDeltails = res.data
      })
    },
    search(val) {  // 搜索
      let _this = this
      _this.queryParam = val
      _this.$refs.table.refresh(true)
      _this.getSubtotalDeltails()
    },
    handleEdit(record) {
      this.visible = true
      this.form = { ...record }
      this.$console(this.form)
    },
    handleOk() {
      this.$refs.form1.validate(valid => {
        if (valid) {
          let statuData = {}
          statuData.id = this.form.id
          statuData.statusId = this.statusCodes.find(item => this.form.statusCode === item.code)?.id
          // statuData.statusCode = this.form.statusCode
          statuData.timeCode = this.form.timeCode
          this.loading = true
          editLaborSubcontractors(statuData).then(res => {
            this.loading = false
            if (res.code == 200) {
              this.visible = false
              this.$message.success('状态变更成功')
              this.getSubtotalDeltails()
              this.$refs.table.refresh(true)
            }
          }).catch(res => {
            this.$message.warning('状态变更失败')
            this.loading = false
          })
        }
      })
    },
    handleCancel() {
      this.visible = false
    },
    handleSub(record) {
      this.visibles = true
      this.mdls = { ...record }
    },
    handleCancels() {
      this.visibles = false
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date())
      }
    }
  }
}
</script>


